<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="名称" prop="dataSourceName">
        <el-input
          v-model="queryParams.dataSourceName"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.data_base_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="实例" prop="dataType">
        <el-select
          v-model="queryParams.dataType"
          placeholder="请选择实例"
          clearable
        >
          <el-option
            v-for="dict in dict.type.database_datatype"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.data_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8 bottom-20">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['console:datasourceInfo:add']"
          >新增</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          size="mini"
          type="danger"
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['console:datasourceInfo:remove']"
          >删除</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="datasourceInfoList"
      @selection-change="handleSelectionChange"
      ref="moviesTable"
    >
      <template slot="empty">
        <el-empty :image-size="100" description="暂无数据"></el-empty>
      </template>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="55">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)"></span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="dataSourceName" />
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.data_base_type"
            :value="scope.row.type"
          />
        </template>
      </el-table-column>
      <el-table-column label="ip" align="center" prop="ip" />
      <el-table-column label="端口" align="center" prop="port" />
      <el-table-column label="数据库" align="center" prop="databaseName" />
      <el-table-column label="联通状态" align="center" prop="testStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.database_datataststatus"
            :value="scope.row.testStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.data_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="150px"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-data-line"
            size="mini"
            @click="handleTest(scope.row)"
            >测试</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['console:datasourceInfo:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['console:datasourceInfo:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pgNum"
      :limit.sync="queryParams.pgSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据源信息对话框 -->
    <el-dialog
      :title="title"
      width="850px"
      append-to-body
      :visible.sync="NextdataDialog"
      :close-on-click-modal="false"
    >
      <ChangeDatasouceInfoVue
        :key="form.type"
        :title="title"
        :form="form"
        :type="form.type"
        ref="formRef"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="testConnect">测试连接</el-button>
        <el-button v-if="gobackState" type="primary" @click="goBack"
          >上一步</el-button
        >
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="新增实例"
      :close-on-click-modal="false"
      :visible.sync="open"
      width="800px"
    >
      <el-row>
        <el-form
          :model="form"
          :inline="true"
          label-position="right"
          ref="form"
          class="form"
        >
          <el-col :span="12">
            <el-form-item prop="type">
              <el-input
                @input="handleDatabaseType"
                v-model="form.type"
                placeholder="请输入数据库类型"
                style="width: 400px; margin-left: 70px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="dataType" style="margin-left: 50px">
              <el-select
                v-model="form.dataType"
                placeholder="请选择类型"
                style="width: 200px; margin-left: 70px"
                @change="dataTypeChange"
              >
                <el-option
                  v-for="dict in dict.type.database_datatype"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row>
        <el-col
          style="width: 100px; height: 100px; margin: 15px"
          v-for="dict in filterDatabaseTypeList"
          :key="dict.value"
        >
          <el-card
            shadow="hover"
            :style="{
              width: '100px',
              height: '100px',
              border:
                form.type && dict.value.toLowerCase() == form.type.toLowerCase()
                  ? '1px solid #666'
                  : '1px solid #eee',
            }"
            :body-style="{ padding: '0px' }"
            @click.native="handleType(dict)"
          >
            <img :src="dict.cssClass" alt width="100px" height="70px" />
            <div style="text-align: center">
              <span>{{ dict.value }}</span>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="open = false">取 消</el-button>
        <el-button type="primary" @click="openNext()">下一步</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDatasourceInfo,
  getDatasourceInfo,
  delDatasourceInfo,
  addDatasourceInfo,
  updateDatasourceInfo,
  databaseCheck,
} from "@/api/console/datasourceInfo";

import ChangeDatasouceInfoVue from "./components/changeDatasouceInfo.vue";

export default {
  name: "DatasourceInfo",
  components: { ChangeDatasouceInfoVue },
  dicts: [
    "database_case_sensitive",
    "data_status",
    "data_base_type",
    "database_auto_commit",
    "database_datatype",
    "database_datataststatus",
    "dabase_show",
    "instancename_show",
    "field_case",
    "objectname_quote",
  ],
  data() {
    return {
      databaseTypeActive: false,
      oracleTypeList: [
        {
          value: "serviceName",
          label: "服务名",
        },
        {
          value: "sid",
          label: "SID",
        },
      ],
      oracleType: "serviceName",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据源信息表格数据
      datasourceInfoList: [],

      amountError: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      NextdataDialog: false,
      // 查询参数
      queryParams: {
        pgNum: 1,
        pgSize: 10,
        dataSourceName: null,
        type: null,
        status: null,
        dataType: "2",
      },
      showConf: false,
      // 表单参数
      form: {},
      formType: {},
      gobackState: true,
      myType: "",
      data_typeList: [],
      dirUrl: [],
      resultName: "",
      url: [],
      myurl: "",
      databaseTypeList: [],
      filterDatabaseTypeList: [],
    };
  },
  created() {
    this.getList();
  },

  mounted() {
    this.updataUrl();
  },
  watch: {
    "form.ip": "updataUrl",
    "form.port": "updataUrl",
    "form.databaseName": "updataUrl",
    "form.schemaName": "updataUrl",
    "form.useUnicode": "updataUrl",
    "form.encoding": "updataUrl",
    "form.serviceName": "updataUrl",
    "form.sid": "updataUrl",
    oracleType: "updataUrl",
    "form.GBASEDBTSERVER":"updataUrl"
  },
  methods: {
    //获取表格序号
    getIndex($index) {
      return (
        (this.queryParams.pgNum - 1) * this.queryParams.pgSize + $index + 1
      );
    },
    updataUrl() {
      if (!this.form.type) {
        return;
      }
      let that = this;
      let baseUrl = `${this.myurl}${this.form.ip ? this.form.ip : ""}:${
        this.form.port ? this.form.port : ""
      }`;
      console.log(this.form);

      let url = {
        MYSQL: () =>
          (baseUrl += this.form.databaseName
            ? `/${this.form.databaseName || ""}`
            : ""),
        ORACLE: () => {
          if (this.oracleType == "sid") {
            baseUrl += `:${this.form.sid || ""}`;
          } else if (this.oracleType == "serviceName") {
            baseUrl += `/${this.form.serviceName || ""}`;
          }
          return baseUrl;
        },
        OSCAR: () => {
          if (this.oracleType == "sid") {
            baseUrl += `:${this.form.sid || ""}`;
          } else if (this.oracleType == "serviceName") {
            baseUrl += `/${this.form.serviceName || ""}`;
          }
          return baseUrl;
        },
        DAMENG: () =>
          (baseUrl += this.form.schemaName
            ? `?schema=${this.form.schemaName || ""}`
            : ""),
        KINGBASE: () =>
          (baseUrl += this.form.databaseName
            ? `/${this.form.databaseName || ""}`
            : ""),
        SQLSERVER: () =>
          `${baseUrl};${
            this.form.databaseName
              ? `databaseName=${this.form.databaseName};`
              : ""
          }`,
        GBASE: () =>
          `${baseUrl}/${this.form.schemaName ? this.form.schemaName : ""}:${
            this.form.GBASEDBTSERVER
              ? `GBASEDBTSERVER=${this.form.GBASEDBTSERVER};`
              : ""
          }SQLMODE=GBase;`,
      };
      let queryParts = [
        this.form.useUnicode === "true" || this.form.useUnicode === "false"
          ? `useUnicode=${this.form.useUnicode}`
          : ``,
        this.form.encoding ? `characterEncoding=${this.form.encoding}` : "",
      ]
        .filter((part) => part)
        .join("&");
      this.form.url = `${url[that.form.type.toUpperCase()]()}${
        queryParts ? "?" + queryParts : ""
      }`;

      return;
    },
    dataTypeChange() {
      this.$forceUpdate();
    },
    /** 查询数据源信息列表 */
    getList() {
      this.loading = true;
      listDatasourceInfo(this.queryParams).then((response) => {
        this.datasourceInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.NextdataDialog = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dataSourceName: null,
        type: null,
        driver: null,
        ip: null,
        port: null,
        database: null,
        uname: null,
        pwd: null,
        caseSensitive: null,
        autoCommit: null,
        connectTimeout: null,
        socketTimeout: null,
        encoding: null,
        useUnicode: null,
        url: null,
        testStatus: null,
        status: this.dict.type.data_status[0].value,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        fieldCase: this.dict.type.field_case[0].value,
        remark: null,
        quote: this.dict.type.objectname_quote[0].value,
        schema: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pgNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      let res = await this.getDicts("data_base_type");
      this.filterDatabaseTypeList = [];
      res.data.forEach((f) => {
        this.filterDatabaseTypeList.push({
          label: f.dictLabel,
          value: f.dictValue,
          cssClass: f.cssClass,
        });
      });
      this.databaseTypeList = this.filterDatabaseTypeList;
      // console.log(res);
      this.open = true;
      this.title = "添加数据源信息";
      this.gobackState = true;
      this.form.dataType = 2;
      // this.form = {
      // };
      // this.form.status = this.dict.type.data_status[0].value;
    },
    /** 修改按钮操作 详情 */
    handleUpdate(row) {
      this.gobackState = false;
      this.getDicts("data_type_conf").then((response) => {
        this.dirUrl = response.data;
        this.dirUrl.forEach((item) => {
          if (item.dictLabel == row.type) {
            this.resultName = item.dictValue;
          }
        });
        this.getDicts(this.resultName).then((response) => {
          response.data.forEach((item) => {
            if (item.dictLabel == "urlprefix") {
              this.myurl = item.dictValue;
              return;
            }
            this.form[item.dictLabel] = item.dictValue;
          });
        });
      });
      let data = {
        id: row.id || this.ids,
      };
      getDatasourceInfo(data).then((response) => {
        this.form = response.data;
        this.NextdataDialog = true;
        this.title = "修改数据源信息";
        if (this.form["sid"]) {
          this.oracleType = "sid";
        }
        if (this.form["serviceName"]) {
          this.oracleType = "serviceName";
        }
      });
      let data1 = {
        type: row.type,
        dataType: 1,
      };
      listDatasourceInfo(data1).then((response) => {
        this.data_typeList = response.rows;
      });
      this.reset();
    },
    handleTest(row) {
      let data = {
        id: row.id,
      };
      databaseCheck(data).then((response) => {
        if (response.data.code == 200) {
          this.$message({
            message: "连接成功",
            type: "success",
          });
          this.getList();
        } else {
          this.$message.error("连接失败");
          this.getList();
        }
      });
    },

    // 上一步
    goBack() {
      this.open = true;
      this.NextdataDialog = false;
      this.$nextTick(() => this.reset());
      this.handleDatabaseType("");
    },
    testConnect() {
      const {
        type,
        ip,
        port,
        uname,
        pwd,
        databaseName,
        version,
        encoding,
        useUnicode,
        connectTimeout,
        socketTimeout,
        driver,
        url,
      } = this.form;
      databaseCheck({
        type,
        ip,
        port,
        uname,
        pwd,
        databaseName,
        version,
        encoding,
        useUnicode,
        connectTimeout,
        socketTimeout,
        driver,
        url,
      }).then((response) => {
        if (response.data.code == 200) {
          this.$message({
            message: "连接成功",
            type: "success",
          });
          this.form.testStatus = 0;
          this.getList();
        } else {
          this.form.testStatus = 1;
          this.$message.error(response.data.msg);
          this.getList();
        }
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs.formRef.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.oracleType) {
            this.form[this.form.oracleType == "sid" ? "sid" : "serviceName"] =
              this.form.serviceName;
            delete this.form[
              this.form.oracleType == "sid" ? "serviceName" : "sid"
            ];
          }
          if (this.form.id != null) {
            let data = {
              id: this.form.id,
              dataSourceName: this.form.dataSourceName,
              type: this.form.type,
              driver: this.form.driver,
              ip: this.form.ip,
              port: this.form.port,
              databaseName: this.form.databaseName,
              catalogName: "",
              schemaName: this.form.schemaName,
              uname: this.form.uname,
              pwd: this.form.pwd,
              caseSensitive: this.form.caseSensitive,
              autoCommit: this.form.autoCommit,
              connectTimeout: this.form.connectTimeout,
              socketTimeout: this.form.socketTimeout,
              encoding: this.form.encoding,
              useUnicode: this.form.useUnicode,
              url: this.form.url,
              testStatus: this.form.testStatus,
              status: this.form.status,
              dataType: this.form.dataType,
              fieldCase: this.form.fieldCase,
              quote: this.form.quote,
              sid: this.form.sid,
              serviceName: this.form.serviceName,
              // schema: this.form.schema,
            };
            updateDatasourceInfo(data).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.NextdataDialog = false;
              this.getList();
            });
          } else {
            let data = {
              dataSourceName: this.form.dataSourceName,
              type: this.form.type,
              driver: this.form.driver,
              ip: this.form.ip,
              port: this.form.port,
              databaseName: this.form.databaseName,
              catalogName: "",
              schemaName: this.form.schemaName,
              uname: this.form.uname,
              pwd: this.form.pwd,
              caseSensitive: this.form.caseSensitive,
              autoCommit: this.form.autoCommit,
              connectTimeout: this.form.connectTimeout,
              socketTimeout: this.form.socketTimeout,
              encoding: this.form.encoding,
              useUnicode: this.form.useUnicode,
              url: this.form.url,
              testStatus: this.form.testStatus,
              status: this.form.status,
              dataType: this.form.dataType,
              fieldCase: this.form.fieldCase,
              quote: this.form.quote,
              sid: this.form.sid,
              serviceName: this.form.serviceName,
            };
            addDatasourceInfo(data).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.NextdataDialog = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.ids.push(row.id);
      let data = {
        ids: this.ids,
      };
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          return delDatasourceInfo(data);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    handleType(type) {
      this.form.type = type.value;
    },
    // 下一步
    openNext() {
      if (
        !this.databaseTypeList.find(
          (f) => f.value.toLowerCase() == this.form.type.toLowerCase()
        )
      ) {
        this.$message("数据源类型不能为空");
        this.open = true;
        return;
      }
      console.log(78979);
      this.open = false;
      this.NextdataDialog = true;
      let data = {
        type: this.form.type,
        dataType: 1,
      };
      listDatasourceInfo(data).then((response) => {
        this.data_typeList = response.rows;
      });
      this.getDicts("data_type_conf").then((response) => {
        this.dirUrl = response.data;
        this.dirUrl.forEach((item) => {
          console.log(item.dictLabel);
          if (item.dictLabel.toLowerCase() == this.form.type.toLowerCase()) {
            this.resultName = item.dictValue;
          }
        });
        if (!this.resultName) return;
        this.getDicts(this.resultName).then((response) => {
          response.data.forEach((item) => {
            if (item.dictLabel == "urlprefix") {
              this.myurl = item.dictValue;
              return;
            }
            this.form[item.dictLabel] = item.dictValue;
          });
        });
      });
    },
    handleDatabaseType(v) {
      let restaurants = this.databaseTypeList;
      this.filterDatabaseTypeList = v
        ? restaurants.filter(this.createFilter(v))
        : restaurants;
    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant.label
          .toLowerCase()
          .includes(queryString.toLowerCase());
      };
    },
    data_TypeChange(row) {
      row.id = null;
      row.autoCommit = "";
      row.caseSensitive = "";
      row.dataType = this.form.dataType;

      this.form = row;
    },
    numberInputOnlyNumbers(event) {
      // 允许输入数字、退格键和剪贴板操作
      if (
        !/^(\d|Backspace|Cut|Paste)$/i.test(event.key) &&
        !(event.key === "Unidentified" && event.location === 3)
      ) {
        event.preventDefault();
      }
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-collapse-item__wrap {
  padding: 0 15px;
  border-bottom: none !important;
}

h3 {
  font-size: 16px;
  font-weight: 600;
}

::v-deep .el-card:hover {
  box-shadow: 0px 0px 5px 0px #aaa;
}
</style>
